<?php
// Version
define('VERSION', '0.1');

// Configuration
require_once('config.php');

// Startup
require_once(DIR_SYSTEM.'startup.php');

// Application Classes

// Registry
$registry = new Registry();

// Loader
$loader = new Loader($registry);
$registry->set('load', $loader);

$config=new Config();
$registry->set('config', $config);
$config->set("config_error_display",'TRUE');
//$config->set("config_error_display",'FALSE');
// Database
$db = new DB(DB_DRIVER, DB_HOSTNAME, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
$registry->set('db', $db);

//Log File
$log = new Log("error.txt");
$registry->set('log', $log);

// Error Handler
function error_handler($errno, $errstr, $errfile, $errline) {
	global $config, $log;

	switch ($errno) {
		case E_NOTICE:
		case E_USER_NOTICE:
			$error = 'Notice';
			break;
		case E_WARNING:
		case E_USER_WARNING:
			$error = 'Warning';
			break;
		case E_ERROR:
		case E_USER_ERROR:
			$error = 'Fatal Error';
			break;
		default:
			$error = 'Unknown';
			break;
	}
	if ($config->get('config_error_display')=="TRUE") {
		echo '<b>' . $error . '</b>: ' . $errstr . ' in <b>' . $errfile . '</b> on line <b>' . $errline . '</b>';
	}
	else{
		die("Page not found on server or Error occuried!");
	}
	if ($config->get('config_error_log')) {
		$log->write('PHP ' . $error . ':  ' . $errstr . ' in ' . $errfile . ' on line ' . $errline);
	}
	return TRUE;
}

set_error_handler('error_handler');

// Request
$request = new Request();
$registry->set('request', $request);

// Response
$response = new Response();
$response->addHeader('Content-Type: text/html; charset=utf-8');
$registry->set('response', $response);

// Cache
$registry->set('cache', new Cache());

// Session
$session = new Session();
$registry->set('session', $session);



// Document
$registry->set('document', new Document());

// Front Controller
$controller = new Front($registry);

//User
$user=new User($registry);
$registry->set('user',$user);

$arg=array();
$loader->library('uri');
$url=new uri();
$strurl=$url->_detect_uri();
$segment=$url->_explode_segments();
if(count($segment)>2){
  $arg=array_splice($segment,2);
}
// Router
if (isset($strurl) && $strurl!="/") {
	$action = new Action($strurl,$arg);
} else {
	$action = new Action('login');
}

$controller->dispatch($action, new Action('not_found'));

$response->output();
?>